﻿using System;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using TMPro;

namespace Core
{
    public class ButtonEx : BaseUI
    {
        private Button _btn;
        [HideInInspector]
        public Button btn
        {
            get
            {
                if (_btn == null)
                    _btn = GetComponent<Button>();
                return _btn;
            }
        }

        private TextMeshProUGUI _txt;
        [HideInInspector]
        public TextMeshProUGUI txt
        {
            get
            {
                if (_txt == null)
                    _txt = GetComponent<TextMeshProUGUI>();
                return _txt;
            }
        }

        private ImageEx _imgEx;
        [HideInInspector]
        public ImageEx imgEx
        {
            get
            {
                if (_imgEx == null)
                    _imgEx = GetComponent<ImageEx>();
                return _imgEx;
            }
        }

        private long lastClickTime;
        // 点击冷却时间（毫秒）
        private int countdownTime = 500;

        private UnityAction m_clickAction;
        private Action m_onClick;
        public Action onClick
        {
            get
            {
                return m_onClick;
            }
            set
            {
                m_onClick = value;
                if (btn == null)
                {
                    Debug.LogError("btn is null");
                    return;
                }

                if (m_clickAction != null)
                    return;

                m_clickAction = new UnityAction(() =>
                {
                    var span = DateTime.Now.Ticks - lastClickTime;
                    if (span < countdownTime)
                        return;
                    lastClickTime = DateTime.Now.Ticks;

                    if (m_onClick != null)
                        m_onClick();
                });

                btn.onClick.AddListener(m_clickAction);
            }
        }
    }
}
